package com.dl.base.ui

import android.os.Bundle
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment

abstract class BaseFragment<T : ViewDataBinding> : Fragment() {
    private var isFirstLoad = true
    lateinit var viewBinding: T

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewBinding = DataBindingUtil.inflate(inflater, setContentView(), container, false)
        return viewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init(arguments)
        Looper.myQueue().addIdleHandler {
            lazyInit(savedInstanceState)
            false
        }
    }

    override fun onResume() {
        super.onResume()
        if (isFirstLoad) {
            whenFistLoad()
            isFirstLoad = false
        } else {
            whenNotFistLoad()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        isFirstLoad = true
    }

    protected fun navBackStack() {
        requireActivity().onBackPressed()
    }

    abstract fun setContentView(): Int
    abstract fun init(arguments: Bundle?)

    /**
     * 第一次加载Fragment时执行
     */
    open fun whenFistLoad() {}

    /**
     * 不是第一次加载Fragment时执行
     */
    open fun whenNotFistLoad() {}

    /**
     * 主线程空闲使运行执行的初始化操作
     */
    open fun lazyInit(bundle: Bundle?) {}

    open fun enableEventBus(): Boolean = false
}